$(document).ready(function(){
	getCoupon();
});

function getCoupon(){
	$('#table_list').DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'../static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/coupon/coupon-list',
            type:'post',
            data:function(d){
            	d.type = $('#search_type').val();
            	d.title = $('#search_title').val();
            },
            error:getError
        },
        aoColumns: [
            { "data": "id", "bSortable": false},
            { "data": "type", "bSortable": false},
            { "data": "title", "bSortable": false },
            { "data": "highlight", "bSortable": false},
            { "data": "coupon_time", "bSortable": false},
            { "data": "release_number", "bSortable": false},
            { "data": "draw_count", "bSortable": false},
            { "data": "use_mark", "bSortable": false},
            { "data": "use_flg", "bSortable": false},
            { "data": "id", "bSortable": false}
        ],
        columnDefs: [
        	{
                "targets": [8],
                "data": "use_flg",
                "render": function(data, type, full) {
                    return html = '<span class="switch" data-id="'+ full.id +'" data-flg="'+(data == 1 ? 0 : 1)+'"><input  style="width:20px;height:20px;" type="checkbox" '+(data == 1 ? 'checked="checked"' : '')+' class="input-check"></span>';
                }
            },
            {
                "targets": [9],
                "data": "use_flg",
                "render": function(data, type, full) {
                    return html = '<a href="javascript:" onclick="couponDetail('+ full.id +')">修改</a>';
                }
            },
        ]
    });
}

function table_list_reload(){
	var table = $('#table_list').DataTable();
    table.ajax.reload();
}

$('#reset_button').click(function(){
	$('#search_type').val('');
	$('#search_title').val('');
    table_list_reload();
});

$('.add_coupon').on('click',function(){
	$('#type').val('');
	$('#title').val('');
	$('#highlight').val('');
	$('#reservationtime').daterangepicker({
	    language:  'zh-CN',
	    timePicker: true,
	    timePickerIncrement: 30,
	    format: 'YYYY-MM-DD',
	    locale: {
	        format: 'YYYY-MM-DD',
	        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
	        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
	    }
	});
	$('#content').val('');
	$('#input_table').find('tbody').html('');
	$('#input_table_sku').find('tbody').html('');
	$('#release_number').val('');
	var html = '<label for="tag_group_id_add"><span class="text-danger">* </span>使用标识</label><div class="use_mark_class" style="width:50%"><select style="display:none;" name="use_mark" multiple id="use_mark" placeholder="请选择">';
	for(key in use_mark){
		html += '<option value="'+key+'">'+use_mark[key]+'</option>';
	}
	html += '</div>';
	$('#use_mark_div').html(html);
	$('.use_mark_class').dropdown({
		limitCount: 40,
		multipleMode: 'label',
		choice: function() {
		}
	});
	$('#use_flg').val(1);
	$('#coupon_id').val('');
	$('#coupon-modal').modal('show');
});

function changeCouponStatus(id,use_flg){
	if(use_flg == 1){
		title = '确定启用此优惠券吗？';
	}else{
		title = '确定禁用此优惠券吗？';
	}
	$.jBox.confirm(title, "提示", function(v){
        if (v == 'ok'){
            $.post('/coupon/change-coupon-status',{id:id,use_flg:use_flg},success,'json');
            return false;
            function success(data){
                $.jBox.close();
                if(data.code == 200)
                {
                    $.jBox.tip('处理成功', 'success');
                    window.setTimeout(function () { table_list_reload(); }, 1000);
                }
                else{
                    $.jBox.error(data.val, '错误');
                }
            }
        }else{
        	$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',(use_flg == 1 ? false : true));
            $.jBox.close();
        }
    });
}

function couponDetail(id){
	$.post('/coupon/coupon-detail',{id:id},success,'json');
	function success(data){
    	if(data.code == 200){
    		var result = data.val;
    		$('#coupon-modal').modal('show');
    		$('#type').val(result.type);
    		$('#title').val(result.title);
    		$('#highlight').val(result.highlight);
    		$('#reservationtime').daterangepicker({
    			startDate:result.coupon_start_time,
    			endDate:result.coupon_end_time,
    		    language:  'zh-CN',
    		    timePicker: true,
    		    timePickerIncrement: 30,
    		    format: 'YYYY-MM-DD',
    		    locale: {
    		        format: 'YYYY-MM-DD',
    		        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
    		        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    		    }
    		});
    		$('#content').val(result.content);
    		var detail = result.plus;
    		var html_category,html_sku;
    		$('#input_table').find('tbody').html('');
    		$('#input_table_sku').find('tbody').html('');
    		if(detail.length > 0)detail.forEach(function(full,index){
    			var html = '';
    			var class_len = $('#class_len').val();
    			var div_class = 'dropdown-sin-'+class_len;
        		if(full.type == '2'){
    				html += '<tr><td><input type="hidden" name="coupon_plus_1[]" value="'+full.id+'">';
    				html += '<div class="'+div_class+'">';
    			 	html += '<select style="display:none" name="category[]" placeholder="请选择">';
    			 	for(key in category){
    			 		html += '<option value="'+key+'" '+(key == full.category_id ? 'selected' : '')+'>'+category[key]+'</option>';
    			 	}
    		    	html += '</select>';
    		    	html += '</div>';
    		    	html += '</td>';
    		    	html += '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td></tr>';
        		    $('#input_table').find('tbody').append(html);
        		    $('.'+div_class).dropdown({
        		        readOnly: true,
        		        input: '<input type="text" maxLength="20" placeholder="请输入搜索">'
        		 	});
            	}else if(full.type == '1'){
            		html += '<tr><td><input name="sku[]" value="'+full.sku+'" class="form-control"><input type="hidden" name="coupon_plus_2[]" value="'+full.id+'"></td>';
            		html += '<td>'+full.goods_name_cn+'</td>';
                	html += '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td></tr>';
                	$('#input_table_sku').find('tbody').append(html);
				}
        		class_len++;
        		$('#class_len').val(class_len);
        	});
    		$('#release_number').val(result.release_number);
    		if(result.use_mark.length > 0){
    			var html = '<label for="tag_group_id_add"><span class="text-danger">* </span>使用标识</label><div class="use_mark_class" style="width:50%"><select style="display:none;" name="use_mark" multiple id="use_mark" placeholder="请选择">';
    			for(key in use_mark){
    				html += '<option value="'+key+'" '+($.inArray(key,result.use_mark) != -1 ? 'selected' : '')+'>'+use_mark[key]+'</option>';
    			}
    			html += '</div>';
    			$('#use_mark_div').html(html);
    			$('.use_mark_class').dropdown({
    				limitCount: 40,
    				multipleMode: 'label',
    				choice: function() {
    				}
    			});
    		}
        	$('#use_flg').val(result.use_flg);
        	$('#coupon_id').val(result.id);
        	$('#input_table_sku').find('input[name="sku[]"]').blur(function(){
            	var where = $(this);
        		var sku = where.val();
        		validateSku(sku,where);
        	});
        }else{
        	$.jBox.error(data.val, '错误');
        }
    }
}

$('#table_list').on('click','.input-check',function(){
	var id = $(this).parent().attr('data-id');
	var use_flg = $(this).parent().attr('data-flg');
	changeCouponStatus(id,use_flg);
});

$('#add_input').click(function(){
	var class_len = $('#class_len').val();
	var div_class = 'dropdown-sin-'+class_len;
	var html = '<tr><td><input type="hidden" name="coupon_plus_1[]" value="0">';
		html += '<div class="'+div_class+'">';
	 	html += '<select style="display:none" name="category[]" placeholder="请选择">';
	 	for(key in category){
	 		html += '<option value="'+key+'">'+category[key]+'</option>';
	 	}
		html += '</select>';
		html += '</div>';
		html += '</td>';
		html += '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td></tr>';
	    $('#input_table').find('tbody').append(html);
	    $('.'+div_class).dropdown({
	    	readOnly: true,
	        input: '<input type="text" maxLength="20" placeholder="请输入搜索">'
	    });
    class_len++;
    $('#class_len').val(class_len);
});

$('#add_input_sku').click(function(){
	var class_len = $('#class_len').val();
	var div_class = 'dropdown-sin-'+class_len;
	var html = '<tr><td><input name="sku[]" value="" class="form-control"><input type="hidden" name="coupon_plus_2[]" value="0"></td>';
		html += '<td></td>';
    	html += '<td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td></tr>';
    $('#input_table_sku').find('tbody').append(html);
    $('.'+div_class).dropdown({
        readOnly: true,
        input: '<input type="text" maxLength="20" placeholder="请输入搜索">'
	});
    class_len++;
    $('#class_len').val(class_len);
    $('#input_table_sku').find('input[name="sku[]"]').blur(function(){
    	var where = $(this);
		var sku = where.val();
		validateSku(sku,where);
	});
});

$(function(){
	$('.use_mark_class').dropdown({
		limitCount: 40,
		multipleMode: 'label',
		choice: function() {
		}
	});
	
	$('#reservationtime').daterangepicker({
	    language:  'zh-CN',
	    timePicker: true,
	    timePickerIncrement: 30,
	    format: 'YYYY-MM-DD',
	    locale: {
	        format: 'YYYY-MM-DD',
	        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
	        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
	    }
	});
});

$('.upload-img-btn').click(function(){
    $('.upload_file').trigger('click');
});

$('.upload_file').change(function(){
	$('#upload_form_update').submit();
});

$('#upload_form_update').submit(function(e){
    e.preventDefault();
    $.ajaxFileUpload({
		url: '/coupon/excel-file-upload',
		secureuri: false,
		fileElementId: 'file',
		dataType: 'json',
		success: function (data, status){
			if (data.code == 200) {
				$('#input_table_sku').find('tbody').html('');
				var result = data.val;
				result.forEach(function(data,index){
					var html = '';
					html += '<tr class="'+data.sku+'">';
					html += '<td><input name="sku[]" value="'+data.sku+'" class="form-control"><input name="coupon_plus_2[]" value="" type="hidden"></td>';
					html += '<td></td><td><a href="javascript:;" class="up_input_table_tr">上移</a> <a href="javascript:;" class="down_input_table_tr">下移</a> <a class="del_input_table_tr" href="javascript:;">删除</a></td>';
					html += '</tr>';
					$('#input_table_sku').find('tbody').append(html);
					where = $('.'+data.sku).find('input[name="sku[]"]');
					validateSku(data.sku,where);
				});
				$('#input_table_sku').find('input[name="sku[]"]').blur(function(){
	            	var where = $(this);
	        		var sku = where.val();
	        		validateSku(sku,where);
	        	});
			} else {
				$.jBox.error(data.val, '错误');
			}
		},
		error: function (data, status, e){
			$.jBox.error(status, '错误');
		}
	});
});

$('table').delegate('.del_input_table_tr','click',function(){
    $(this).parent().parent().remove();
});

$('table').delegate('.up_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').index();
    if(eval(tr_index) == 0){
        return true;
    }else{
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').prev().before(obj);
        $(this).parents('tr').remove();
    }
});

$('table').delegate('.down_input_table_tr','click',function(){
    var tr_index = $(this).parents('tr').next().index();
    if(eval(tr_index) > eval(-1)){
        var obj = $(this).parents('tr').clone();
        $(this).parents('tr').next().after(obj);
        $(this).parents('tr').remove();
    }
});

function validateSku(sku,where){
	if(sku == '' || sku == undefined){
		return false;
	}
	$.post('/coupon/validate-sku',{sku:sku},success,'json');
	function success(data){
    	if(data.code == 200){
    		where.parent().next().text(data.val);
        }
    }
}

$('.ajax_post_tag').on('click',function(){
	var form = $('#coupon_form');
	var type = $('#type').val();
	if(type == ''){
        $.jBox.error('请选择优惠券类型', '错误');
        return false;
    }
	var title = $('#title').val();
    if(title == ''){
        $.jBox.error('请填写优惠卷名称', '错误');
        return false;
    }
    var highlight = $('#highlight').val();
    if(highlight == ''){
        $.jBox.error('请填写优惠券重点突出', '错误');
        return false;
    }
    var reservationtime = $('#reservationtime').val();
    if(reservationtime == ''){
        $.jBox.error('请选择优惠券有效日期', '错误');
        return false;
    }
    var content = $('#content').val();
    if(content == ''){
    	$.jBox.error('请填写优惠券描述', '错误');
        return false;
    }
    var category_len = $('#input_table').find('tr').length;
    var sku_len = $('#input_table_sku').find('tr').length;
    if(category_len <= 1 && sku_len <= 1){
        $.jBox.error('请添加至少填写一个分类或商品', '错误');
        return false;
    }
    var release_number = $('#release_number').val();
    if(release_number == '' || release_number == 0){
    	$.jBox.error('请填写优惠券发放张数', '错误');
        return false;
    }
    var use_mark_arr = [];
    $('.use_mark_class').find('.dropdown-selected').each(function(){
    	use_mark_arr.push($(this).find('i').attr('data-id'));
    });
    if(use_mark_arr.length == 0){
    	$.jBox.error('请选择优惠券使用标识', '错误');
        return false;
    }
    $.post(form.attr('action'),form.serialize()+"&use_mark_arr="+use_mark_arr,success,'json');
    return false;
	function success(data){
        if(data.code == 200){
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () {
                $('#coupon-modal').modal('hide');
                table_list_reload();
            }, 1000);
        }else{
            $.jBox.error(data.val, '错误');
        }
	}
});